package com.pomelo.base.core.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 事务管理器
 *
 * @author biankudingcha
 * @date: 2021-07-24
 * @since 0.5.0
 */
public class MultiDataSourceUtil {

    /**
     * 事务
     */
    private static final Map<String, PlatformTransactionManager> TRANSACTION_MANAGER = new ConcurrentHashMap<String, PlatformTransactionManager>();

    /**
     * 设置hibernate LocalSessionFactoryBean
     */
    private static final Map<String, LocalSessionFactoryBean> LOCAL_SESSION_FACTORY_MANAGER = new ConcurrentHashMap<String, LocalSessionFactoryBean>();

    /**
     * 设置数据源事务
     *
     * @param key 数据源
     * @param platformTransactionManager 事务管理器
     */
    synchronized public static void putPlatformTransactionManager(String key,
            PlatformTransactionManager platformTransactionManager) {
        TRANSACTION_MANAGER.put(key, platformTransactionManager);
    }

    /**
     * 获取事务管理器
     *
     * @param key 数据源
     * @return PlatformTransactionManager
     */
    public static PlatformTransactionManager getPlatformTransactionManager(String key) {
        return TRANSACTION_MANAGER.get(key);
    }

    /**
     * 设置LocalSessionFactoryBean
     *
     * @param key 数据源
     * @param sessionFactory LocalSessionFactoryBean
     */
    synchronized public static void putLocalSessionFactory(String key, LocalSessionFactoryBean sessionFactory) {
        LOCAL_SESSION_FACTORY_MANAGER.put(key, sessionFactory);
    }

    /**
     * 获取LocalSessionFactoryBean
     *
     * @param key 数据源
     * @return LocalSessionFactoryBean
     */
    public static LocalSessionFactoryBean getLocalSessionFactory(String key) {
        return LOCAL_SESSION_FACTORY_MANAGER.get(key);
    }
}
